package com.rdc.example.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.*;
import java.util.Properties;

/**
 * @author duck
 * @description 数据库工具类
 */
public class DBUtil {

    private static DruidDataSource dataSource;

    static {
        try {
            Properties prop = new Properties();
            prop.load(Files.newInputStream(Paths.get("src/main/resources/jdbc.properties")));
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws Exception {
        return dataSource.getConnection();
    }

    public static void closeResources(ResultSet rs,PreparedStatement pstmt, Connection conn) throws Exception {
        //检查是否为空再执行，不然狠狠地报空指针异常
        try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}

